﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharePhone.Core.Fields
{
    public class SPLookupField
    {
        public SPLookupField() : this(string.Empty)
        {
        }

        public SPLookupField(string rawFieldValue)
        {
            Values = new Dictionary<int, string>();
            string[] rawValues = rawFieldValue.Split(new[] {";#"}, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < rawValues.Length; i += 2)
            {
                Values.Add(Int32.Parse(rawValues[i]), rawValues[i + 1]);
            }
        }

        public Dictionary<int, string> Values { get; set; }

        /// <summary>
        /// Gets the first lookup value available, if this is a multilookup field - use Values instead.<br/> Returns empty string if no values are present.
        /// </summary>
        public string LookupValue
        {
            get
            {
                if (Values.Count == 0)
                    return string.Empty;
                return Values[Values.Keys.First()];
            }
        }

        /// <summary>
        /// Gets the first lookup ID available, if this is a multilookup field - use Values instead.<br/> Returns -1 if no values are present.
        /// </summary>
        public int LookupId
        {
            get
            {
                if (Values.Count == 0)
                    return -1;
                return Values.Keys.First();
            }
        }

        public void Clear()
        {
            Values = new Dictionary<int, string>();
        }

        /// <summary>
        /// Adds another item as lookup value. Lookup value will be set to empty string temporarily, correct lookup value will be available after a list refresh.
        /// </summary>
        /// <param name="item"></param>
        public void AddLookupValue(BaseItem item)
        {
            if (item.State == ItemState.New)
                throw new ArgumentException("Items in New state are not supported as lookup values");
            if (Values.ContainsKey(item.SPListItemId))
            {
                throw new ArgumentException(
                    string.Format("This item already exists in the lookup collection [List item ID: {0}]",
                                  item.SPListItemId));
            }
            Values.Add(item.SPListItemId, item.Title);
        }

        public override string ToString()
        {
            if (Values.Count == 0)
                return string.Empty;
            var sb = new StringBuilder();
            foreach (int id in Values.Keys)
            {
                sb.Append(string.Format("{0};#{1};#", id, Values[id]));
            }
            string value = sb.ToString();
            return value.Substring(0, value.LastIndexOf(";#"));
        }
    }
}